package com.tyijian.admin.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.validation.Validator;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.tyijian.admin.core.exceptionHandle.RestException;
import com.tyijian.admin.entity.SysRole;
import com.tyijian.admin.entity.SysUser;
import com.tyijian.admin.service.RoleService;
import com.tyijian.admin.service.UserService;
import com.tyijian.springside.core.ResponseBodyBuilder;
import com.tyijian.springside.core.modules.BeanValidators;
import com.tyijian.springside.core.modules.Servlets;
import com.tyijian.springside.core.utils.MediaTypes;

@RestController
@RequestMapping("/api/user")
public class UserController {

	@Autowired
	private UserService userService;

	@Autowired
	private RoleService roleService;

	@Autowired
	private Validator validator;

	/**
	 * 查看用户列表
	 * 
	 * @param pageNumber
	 * @param pageSize
	 * @param sortType
	 * @param request
	 * @return
	 */
	@RequiresPermissions("user:view")
	@RequestMapping(method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8)
	public Page<SysUser> pageList(@RequestParam(value = "page", defaultValue = "1") int pageNumber,
			@RequestParam(value = "pagesize", defaultValue = "10") int pageSize,
			@RequestParam(value = "sortType", defaultValue = "auto") String sortType, ServletRequest request) {

		Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_");
		Page<SysUser> userPage = userService.getUserPageList(searchParams, pageNumber, pageSize, sortType);
		return userPage;
	}

	/**
	 * 根据ID查找用户
	 * 
	 * @param id
	 *            用户ID
	 * @return
	 */
	@RequiresPermissions("user:view")
	@RequestMapping(value = "/{id}", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8)
	public ResponseEntity<?> get(@PathVariable("id") Long id) {
		SysUser user = userService.get(id);
		if (user == null) {
			String message = "用户不存在(id:" + id + ")";
			throw new RestException(HttpStatus.NOT_FOUND, message);
		}
		ResponseEntity<SysUser> response = new ResponseEntity<SysUser>(user, HttpStatus.OK);
		return response;
	}

	/**
	 * 根据loginname 查找用户
	 * 
	 * @param loginname
	 * @return
	 */
	@RequiresPermissions("user:view")
	@RequestMapping(value = "/findByLoginname", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8)
	public ResponseEntity<?> findByLoginname(@RequestParam(value = "loginname", required = true) String loginname) {
		SysUser user = userService.findByLoginname(loginname);
		if (user != null) {
			String message = "登录名称已被使用，请重新设置";
			throw new RestException(HttpStatus.BAD_REQUEST, message);
		}
		ResponseEntity<Map<String, Object>> response = new ResponseEntity<Map<String, Object>>(
				ResponseBodyBuilder.responseSuccessMsg(), HttpStatus.OK);
		return response;
	}

	/**
	 * 根据ID删除用户
	 * 
	 * @param id
	 *            用户ID
	 * @return
	 */
	@RequiresPermissions("user:delete")
	@RequestMapping(value = "/{id}", method = RequestMethod.DELETE, produces = MediaTypes.JSON_UTF_8)
	public ResponseEntity<?> delete(@PathVariable("id") Long id) {
		SysUser user = userService.get(id);
		if (user == null) {
			String message = "用户不存在(id:" + id + ")";
			throw new RestException(HttpStatus.NOT_FOUND, message);
		}
		userService.delete(user);
		ResponseEntity<Map<String, Object>> response = new ResponseEntity<Map<String, Object>>(
				ResponseBodyBuilder.responseSuccessMsg(), HttpStatus.OK);
		return response;
	}

	/**
	 * 创建用户，参数的输入验证交给Validator 来处理
	 * 
	 * @param user
	 *            用户实体
	 * @return
	 */
	@RequiresPermissions("user:create")
	@RequestMapping(method = RequestMethod.POST, consumes = MediaTypes.JSON)
	public ResponseEntity<?> create(@RequestBody SysUser user) {
		// 调用JSR303 Bean Validator进行校验, 异常将由RestExceptionHandler统一处理.
		BeanValidators.validateWithException(validator, user);
		userService.save(user);
		ResponseEntity<SysUser> response = new ResponseEntity<SysUser>(user, HttpStatus.OK);
		return response;
	}
	
	/**
	 * 更新用户，参数的输入验证交给Validator 来处理
	 * 
	 * @param user
	 * @return
	 */
	@RequiresPermissions("user:update")
	@RequestMapping(value = "/{id}",method = RequestMethod.PUT, consumes = MediaTypes.JSON)
	public  ResponseEntity<?> update(@PathVariable("id") Long id,@RequestBody SysUser user) {
		SysUser dbuser = userService.get(id);
		if (dbuser == null) {
			String message = "用户不存在(id:" + id + ")";
			throw new RestException(HttpStatus.NOT_FOUND, message);
		}
		// 调用JSR303 Bean Validator进行校验, 异常将由RestExceptionHandler统一处理.
		user.setId(id);
		BeanValidators.validateWithException(validator, user);
		userService.updateUser(user);
		ResponseEntity<SysUser> response = new ResponseEntity<SysUser>(user, HttpStatus.OK);
		return response;
	}
	
	

	/**
	 * user 赋予角色
	 * 
	 * @param role
	 *            实体
	 * @return
	 */
	@RequiresPermissions("user:create")
	@RequestMapping(value = "/{id}/setRole", method = RequestMethod.POST, consumes = MediaTypes.JSON)
	public ResponseEntity<?> saveUserRole(@PathVariable("id") Long id, @RequestBody SysRole role) {

		if (id == null || role.getId() == null) {
			String message = "请求参数有误";
			throw new RestException(HttpStatus.NOT_FOUND, message);
		}
		List<SysRole> list = new ArrayList<SysRole>();
		SysRole sysrole = roleService.get(role.getId());
		SysUser user=userService.get(id);
		if (user==null||sysrole == null) {
			String message = "用户或角色对象不存在";
			throw new RestException(HttpStatus.NOT_FOUND, message);
		}
		
		list.add(sysrole);
		user.setRoleList(list);
		userService.saveUserRole(user);

		ResponseEntity<Map<String, Object>> response = new ResponseEntity<Map<String, Object>>(
				ResponseBodyBuilder.responseSuccessMsg(), HttpStatus.OK);
		return response;
	}

}